package userlogic

import (
	"context"

	"gitee.com/liuxuezhan/ar-platform/login-rpc/internal/dao/model"
	"gitee.com/liuxuezhan/ar-platform/login-rpc/login_rpc"
	config "gitee.com/liuxuezhan/ar-platform/login-rpc/pkg/code"
	logic "gitee.com/liuxuezhan/ar-platform/login-rpc/pkg/redis_utils"
	"github.com/zeromicro/go-zero/core/logc"

	"gitee.com/liuxuezhan/ar-platform/login-rpc/internal/svc"
	"github.com/zeromicro/go-zero/core/logx"
)

type LogoutAdminLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLogoutAdminLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LogoutAdminLogic {
	return &LogoutAdminLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LogoutAdminLogic) LogoutAdmin(in *login_rpc.LogoutAdminRequest) (*login_rpc.LogoutAdminResponse, error) {
	db := l.svcCtx.Db.Begin()
	if err := model.NewAdminUserModel(l.ctx, db).Logout(in.UserId); err != nil {
		db.Rollback()
		return &login_rpc.LogoutAdminResponse{
			CommonResp: &login_rpc.CommonResp{
				Code:    config.DBError,
				Message: err.Error(),
			},
		}, err
	}

	id, _ := model.NewAdminLoginToken(l.ctx, db).GetAdminUserLoginTokenByUserIdAndSource(in.UserId, in.Source, in.Business)
	if id > 0 {
		if err := model.NewAdminLoginToken(l.ctx, db).UpdateAdminUserLoginToken(id, "", in.UserId); err != nil {
			db.Rollback()
			return &login_rpc.LogoutAdminResponse{
				CommonResp: &login_rpc.CommonResp{
					Code:    config.DBError,
					Message: err.Error(),
				},
			}, err
		}
	}

	redisCli := logic.GetRedisClient(l.svcCtx.Config.RedisConfig)
	_, err := redisCli.Del(l.ctx, logic.BuildRedisKey(l.ctx, in.UserId, true, in.Business, in.Source)).Result()
	if err != nil {
		logc.Errorf(l.ctx, "del admin token from redis err: %v", err)
	}

	db.Commit()
	return &login_rpc.LogoutAdminResponse{
		CommonResp: &login_rpc.CommonResp{
			Code:    0,
			Message: "",
		},
	}, nil
}
